import { reqShopCartList, reqDeleteCart, reqTabChected } from "@/api";
import { getUuid } from "@/utils/uuid_token.js";

const state = {
  //购物车列表数据
  shopCartList: [],
  //uuid 游客临时标识
  uuid_token: getUuid(),
};

const mutations = {
  SHOPCARTD(store, data) {
    store.shopCartList = data;
  },
};

const actions = {
  async reqShopCartList({ commit }) {
    const { data } = await reqShopCartList();
    if (data.code == 200) {
      let body = [];
      if (data.data.length > 0) {
        body = data.data[0].cartInfoList;
      }
      commit("SHOPCARTD", body);
    }
  },
  // eslint-disable-next-line no-unused-vars
  async reqDeleteCart({ commit }, skuId) {
    const { data } = await reqDeleteCart(skuId);
    if (data.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },

  //删除所有选中的商品 promise.all 只要有一个返回是false 就是false
  reqAllDeleteCart({ state, dispatch }) {
    let promiseAll = [];
    state.shopCartList.forEach((ele) => {
      if (ele.isChecked == 1) {
        let promise = dispatch("reqDeleteCart", ele.skuId);
        promiseAll.push(promise);
      }
    });
    return Promise.all(promiseAll);
  },
  //全部选中
  reqAllChecked({ state, dispatch }, isChecked) {
    let promiseAll = [];
    state.shopCartList.forEach((ele) => {
      let promise = dispatch("reqTabChecked", { skuId: ele.skuId, isChecked });
      promiseAll.push(promise);
    });
    return Promise.all(promiseAll);
  },

  async reqTabChecked({ commit }, { skuId, isChecked }) {
    const { data } = await reqTabChected(skuId, isChecked);
    if (data.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error("fail"));
    }
  },
};
const getters = {};

export default {
  state,
  mutations,
  actions,
  getters,
};
